package com.imoblife.brainwavestus;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.imoblife.brainwavestus.model.Constant;
import com.imoblife.brainwavestus.newdownloadframe.DownLoadTaskInfo;
import com.imoblife.brainwavestus.product.ConcreteProduct;
import com.imoblife.brainwavestus.product.Product;
import com.imoblife.brainwavestus.product.ProductInfo;
import com.imoblife.brainwavestus.product.Store;
import com.imoblife.brainwavestus.product.TapJoyInfo;
import com.imoblife.brainwavestus.product.Wave;
import com.imoblife.brainwavestus.product.WaveCollection;
import com.imoblife.brainwavestus.service.DownLoadSchedulerSystem;
import com.imoblife.brainwavestus.user.User;
import com.imoblife.brainwavestus.util.DBUtil;
import com.imoblife.brainwavestus.util.DebugUtil;
import com.imoblife.brainwavestus.util.ProductUtil;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Xml;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

public class LaunchScreenActivity extends BaseActivity {
	
	public static boolean IS_PAD; 
	private final int LAUNCH_MAIN_ACTIVITY = 1;
	private DBUtil mDb;
	private BrainWavestusApplication mBwApplication;
	//Activity启动时的初始时间
	private long mBeginTime = 0;
	//数据加载完成后，需要继续显示公司欢迎界面的时间
	private long mSleepTime = 0;
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			
			switch(msg.what) {
			case LAUNCH_MAIN_ACTIVITY:
				launchMainActivity();
				break;
			}
		}
		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		mDb = new DBUtil(this);
		
		mBwApplication = getBrainWavesApplication();	
		
		getWindow().setFormat(PixelFormat.RGBA_8888);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);
		
		BrainWavestusApplication application 
					= (BrainWavestusApplication)getApplication();
		IS_PAD = application.isPad();
		
		if(IS_PAD) {		
			setContentView(R.layout.pad_initialize_layout);
		}else {
			
			setContentView(R.layout.phone_initialize_layout);
		}
		
		Store store = application.getStore();	
		User user = application.getUser();
		
		if(store != null) {
			
			store.clearProduct();
		}
		
		if(user != null) {
			
			user.clear();
		}
		
		loadProductData();
		
		DownLoadSchedulerSystem.updateUIHandler = new Handler();
		startService(new Intent(this,
				DownLoadSchedulerSystem.class));

	}

	private void loadTapJoyData() {
		
		Long beginTime = System.currentTimeMillis();
		mDb.openForWrite();
		try {
			InputStream inputStream = null;
			inputStream = this.getAssets().open("tb_id.json");
			byte[] data = new byte[inputStream.available()];
			inputStream.read(data);
			String string = new String(data);
			inputStream.close();

			JSONObject jsonObject = new JSONObject(string);
			JSONArray jsonArray = jsonObject.getJSONArray("ItemsArray");

			final int size = jsonArray.length();

			for (int i = 0; i < size; i++) {

				String name = jsonArray.getJSONObject(i).getString("name");
				String tj_id = jsonArray.getJSONObject(i).getString("tj_id");
				
				TapJoyInfo info = new TapJoyInfo(tj_id, name);
				
				mDb.insertTapJoyData(info);		
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mDb.closeDb();
		Long loadTime = System.currentTimeMillis() - beginTime;
		
		DebugUtil.debug(TAG, "load tapjoy data time: " + loadTime);
	}
	
	//加载产品信息
	private void loadProductData() {
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				
				mBeginTime = System.currentTimeMillis();
				
				// if (mBwApplication.isFirstLaunch()) {

				Store store = mBwApplication.getStore();
				User user = mBwApplication.getUser();

				boolean isNeedLoadDataFromDb = false;

				SharedPreferences pref = getSharedPreferences(
						Constant.SHARED_PREFERENCE, 0);

				String language = pref.getString(Constant.LANGUAGE,
						Constant.DEFAULT_LANGUAGE);

				if (language.equals(Constant.DEFAULT_LANGUAGE)
						|| !language.equals(ProductUtil.getLang())) {

					pref.edit().putString(Constant.LANGUAGE,
							ProductUtil.getLang()).commit();

					isNeedLoadDataFromDb = false;
				} else {
					
					DebugUtil.dbDebug(TAG, "isNeedLoadDataFromDb:" + isNeedLoadDataFromDb);
					isNeedLoadDataFromDb = true;
				}

				boolean isLoadFormDbSuccess = false;

				if (isNeedLoadDataFromDb) {

					isLoadFormDbSuccess = mDb.openForRead()
							.loadAllProductsFromDB(store, user);
					
					//加载用户本地已经下载的脑波
					mDb.loadUserLibProduct(store, user);
					mDb.closeDb();
					
					DebugUtil.dbDebug(TAG, "isLoadFormDbSuccess:" + isLoadFormDbSuccess);
				}

				if (!isNeedLoadDataFromDb || !isLoadFormDbSuccess) {

					mDb.deleteDBAndRebuild();

					// 数据库读取数据失败，原因是数据库无数据，需要从xml文件解析
					DebugUtil.dbDebug(TAG, "load data form xml file");
					loadProductFromXmlToDb();
							
					loadTapJoyData();
					
//					ArrayList<Product> products = store
//							.getProductByCategory("getAllCategoryProducts");
//					
//					//加载所有脑波的具体信息非常耗时，不在启动界面加载这些内容
//					//试了一下，并不是因为这里的原因，后面还需要好好优化一下
//					//需要14s的加载时间~
//					Long beginTime = System.currentTimeMillis();
//					
//					for (Product product : products) {
//
//						loadProductDetail(product);
//					}
//					
//					Long loadTime =System.currentTimeMillis() - beginTime;
//					
//					DebugUtil.debug(TAG, "load product detail time:" + loadTime);
				}
				
				//这个暂时每次启动程序都重新加载，后需要把相关信息写入数据库中
				// 加载打折产品、新产品、热销产品等信息
				loadJsonProduct();
				
				//计算加载时间
				long usedTime = System.currentTimeMillis() - mBeginTime;
				
				long sleepTime = Constant.LAUNCH_SCREEN_WAITTING_TIME 
						- usedTime;
				//如果加载数据时间大于规定的显示公司欢迎界面的时间，数据加载完成后，立即显示主界面
				if(sleepTime <= 0){
		
					launchMainActivity();
				}else {
		
					mHandler.sendEmptyMessageDelayed(
									LAUNCH_MAIN_ACTIVITY
									,sleepTime);
				}
				//为了节省加载时间，这里再判断加载一下
//				if (!isNeedLoadDataFromDb || !isLoadFormDbSuccess) {
//							
//					loadTapJoyData();
//				}
				// if(!mDb.loadAllProductsFromDB(store,user)) {
				//
				// //数据库读取数据失败，原因是数据库无数据，需要从xml文件解析
				// DebugUtil.dbDebug(TAG, "load data form xml file");
				// loadProductFromXmlToDb();
				// }
				//
				// loadTapJoyData();

				// }									
			}

		}).start();
	}
	
	private void loadProductDetail(Product product) {
		
		XmlPullParser parser = Xml.newPullParser();

		InputStream fileInputStream = null;
		
		ProductInfo info = product.getProductInfo();
		
		String productName = info.getName();
		
		mDb.openForWrite();
		try {
			fileInputStream = this.getAssets().open(
					"des/" + ProductUtil.getLang() + "/" + productName + ".xml");

			parser.setInput(fileInputStream, "UTF-8");

			while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
				
				String nodeName = parser.getName();
				
				int eventType = parser.getEventType();
				
				switch(eventType) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					if ("brainwave".equals(parser.getName())) {
						
						int attrCount = parser.getAttributeCount();
						
						for (int i = 0; i < attrCount; i++) {

							String attrName = parser.getAttributeName(i);
							String attrValue = parser.getAttributeValue(i);
							setProductDetailInfo(info, attrName, attrValue);				
						}
						
						mDb.updateProduct(info);
						
					} else if ("item".equals(parser.getName())) {
						
						int attrCount = parser.getAttributeCount();
						String name = parser.getAttributeValue(0);
						
						Product item = mBwApplication.getStore().getProductByName(name);
						ProductInfo itemInfo = item.getProductInfo();
						
						for (int i = 0; i < attrCount; i++) {

							String attrName = parser.getAttributeName(i);
							String attrValue = parser.getAttributeValue(i);
							setProductDetailInfo(itemInfo, attrName, attrValue);				
						}
						
						mDb.updateProduct(itemInfo);
					} else if ("detail".equals(parser.getName())) {
						
						info.setLongDescription(parser.nextText());
						
						mDb.updateProduct(info);
					}
					break;
				case XmlPullParser.END_TAG:
					break;
				default:
						break;
				}
				parser.next();
			}
		} catch (IOException e) {

			e.printStackTrace();
		} catch (XmlPullParserException e) {
		
			e.printStackTrace();
		}
		
		mDb.closeDb();
	}
	
	public void parseProductDetailXml(XmlPullParser xp) {

		for (int i = 0; i < xp.getAttributeCount(); i++) {

		}
	}
	
	public void setProductDetailInfo(ProductInfo info, String attrName, String attrValue){
		
		if (attrName.equals("title")) {

			info.setDetailTitle(attrValue);
		} else if (attrName.equals("brainstate")) {

			info.setHzOfProduct(attrValue);
		} else if (attrName.equals("description")) {

			info.setShortDescription(attrValue);
		} else if (attrName.equals("length")) {
			
			info.setSize(attrValue);
		} else if (attrName.equals("price")) {
			
			info.setPriceOfDollar(attrValue);	
			info.setPriceOfGold(ProductUtil.getTUSGold(attrValue));
		} else if (attrName.equals("name")) {
			//这个xml文件中解析出来的name相当于之前products_table.xml中的title
			info.setTitle(attrValue);
		} 
	}
	/**
	 * 启动主程序
	 */
	public void launchMainActivity() {
		
		/* Create an Intent that will start the Main Activity. */
		Intent mainIntent = new Intent(LaunchScreenActivity.this,
				MainActivity.class);
		LaunchScreenActivity.this.startActivity(mainIntent);
		LaunchScreenActivity.this.finish();
	}
	/**
	 * 从xml文件读取产品信息，并添加到数据库中
	 */
	public  void loadProductFromXmlToDb() {
		
		Long begin = System.currentTimeMillis();
		
		try {
			InputStream is = getResources().getAssets()
					.open("des/" + ProductUtil.getLang() 
							+ "/" + Constant.XML_FILE_NAME_OF_PRODUCTS);
			
			DebugUtil.dbDebug(TAG, "language:" + ProductUtil.getLang());
			parserProducts(is);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		Long loadTime = System.currentTimeMillis() - begin;
		
		DebugUtil.debug(TAG, "load product xml time: " + loadTime);
	}
	/**
	 * 解析产品信息
	 * @param is
	 */
	public void parserProducts(InputStream is) {
		// long l = System.currentTimeMillis();
		mDb.openForWrite();
		try {
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(is, "utf-8");
			int eventType = parser.getEventType();
			Product collection = null;
			boolean isCollectionNode = false;
			String collectionCategory = null;
			Store store = getBrainWavesApplication().getStore();
			
			while (eventType != XmlPullParser.END_DOCUMENT) {
				
				String nodeName = parser.getName();

				switch (eventType) {

				case XmlPullParser.START_DOCUMENT:
					break;

				case XmlPullParser.START_TAG:												
					Product product = null;
					ProductInfo productInfo = null;					
					
					//解析产品集信息
					if (nodeName.equals(Constant.PRODUCTS_XML_COLLECTION_TAG)) {

						isCollectionNode = true;
						collection = new WaveCollection();
						productInfo = new ProductInfo();
						productInfo.setIsProductCollection(true);
						
						int attrCount = parser.getAttributeCount();
						
						for (int i = 0; i < attrCount; i++) {

							String attrName = parser.getAttributeName(i);
							String attrValue = parser.getAttributeValue(i);
							setProductInfo(productInfo, attrName, attrValue);

							if (attrName.equals(DBUtil.PRODUCT_CATEGORY)) {
								//记录下当前产品集的名称
								collectionCategory = attrValue;
							}
						}
						
						if(productInfo.getName().equals(Constant.FREE_WAVE_ID)) {
							
							productInfo.setDownloadState(Constant.PRODUCT_STATE_FREE);
						}
						
						collection.setProductInfo(productInfo);		
						
						mDb.insertProduct(productInfo);

					} else if (nodeName
							.equals(Constant.PRODUCTS_XML_PRODUCT_TAG)) {

						product = new Wave();
						productInfo = new ProductInfo();						
						productInfo.setIsProductCollection(false);
						int count = parser.getAttributeCount();

						for (int i = 0; i < count; i++) {

							String attrName = parser.getAttributeName(i);
							String attrValue = parser.getAttributeValue(i);

							setProductInfo(productInfo, attrName, attrValue);
						}
						
						if (isCollectionNode) {

							productInfo.setCategory(collectionCategory);
						}

						product.setProductInfo(productInfo);
						
						//如果当前正在解析产品集节点，则把当前解析的产品添加到产品集
						if(isCollectionNode && collection != null) {
							
							collection.addProduct(product);
						}else {
							
							String category = product.getProductInfo().getCategory();
							DebugUtil.dbDebug(TAG, "add category to store,category:" + category);
							store.addProductToCategory(category,product);
						}
						
						//因为目前送给用户的只有单个的产品，所以如果软件第一次启动，从xml文件加载产品时
						//只在产品解析中加入用户本地曲库
						if(productInfo.getName().equals(Constant.FREE_WAVE_ID)) {
							
							productInfo.setDownloadState(Constant.DOWNLOAD_STATE_START);
							
							DownLoadTaskInfo info = new DownLoadTaskInfo();
							
							info.setTaskName(productInfo.getName() + Constant.MUSIC_FILE_SUFFIX);
							info.setState(Constant.INT_DOWN_STATE_START);
							info.setChangeTime(ProductUtil.long2String(
									System.currentTimeMillis()));
							info.setLevel(DownLoadSchedulerSystem.LEVEL_MUSIC);
							
							mDb.insertNewDownTask(info);
							getBrainWavesApplication().getUser()
								.getLocalLib().addProduct(product);
						}
						
						store.addProduct(productInfo.getName(), product);
															
						mDb.insertProduct(productInfo);												
					}																		
					
					if(product != null) {
						
						
					}
					
					break;

				case XmlPullParser.END_TAG:
					//当解析到产品集结束标志时，把产品集按产品分类和产品名称加入到商店中
					//以分类加入的目的是在所有脑波中，按分类显示时，可以方便的显示出产品
					//以产品名称（也是产品的一个唯一标示）加入商店的目的时，方便通过产品的名称
					//获取产品集对象，以便在打折、促销、新品等分组中方便的显示产品
					if (Constant.PRODUCTS_XML_COLLECTION_TAG.equals(nodeName)) {
						
						DebugUtil.dbDebug("LaunchScreen", "collection end tag");
						store.addProductToCategory(collectionCategory, collection);
						DebugUtil.dbDebug("LaunchScreen", "collectionCategory:"+collectionCategory);
						store.addProduct(collection.getProductInfo().getName(), collection);
						isCollectionNode = false;
						collection = null;
					}
					break;

				default:
					break;
				}

				eventType = parser.next();
			}

			is.close();

		} catch (Exception e) {

			e.printStackTrace();
		}
		mDb.closeDb();
		// ToolsUtil.debug(TAG, "创建 下载数据库" + (System.currentTimeMillis() - l));
	}
	
	public ProductInfo setProductInfo(ProductInfo productInfo, String attrName, String attrValue){

		if (attrName.equals(DBUtil.PRODUCT_CATEGORY)) {
			
			productInfo.setCategory(attrValue);
		} else if (attrName.equals(DBUtil.PRODUCT_NAME)) {	
			
			productInfo.setName(attrValue);
			productInfo.setId(attrValue);
			
		} else if (attrName.equals(DBUtil.PRODUCT_TITLE)) {
			
			productInfo.setTitle(attrValue);
		} else if (attrName.equals(DBUtil.PRODUCT_PARENT)) {
			
			productInfo.setParentId(attrValue);
		}else if (attrName.equals(DBUtil.PRODUCT_FILE_SIZE)) {
			
			productInfo.setSize(attrValue);
		}else if (attrName.equals(DBUtil.PRODUCT_DOWNLOAD_STATE)) {
			
			productInfo.setDownloadState(attrValue);
		}else if (attrName.equals(DBUtil.PRODUCT_VERSION)) {
			
			productInfo.setVersion(attrValue);
		}else if (attrName.equals(DBUtil.PRODUCT_LEVEL)) {
			
			productInfo.setLevel(attrValue);
		}
		
		return productInfo;
	}
	
	public void loadJsonProduct(){
		
		InputStream inputStream = null;
		//暂时不打开测试服务器
//		if (DebugServerPushDataUtil.isOpenProductJsonDebug) {
//			try {
//				inputStream = mActivity.openFileInput("products.json");
//			} catch (Exception e) {
//			}
//		}
		try {
			if (inputStream == null) {
				inputStream = getAssets()
						.open(Constant.JSON_FILE_NAME_OF_STORE_PRODUCT_GROUP);
			} else {
				DebugUtil.storeDebug(TAG, "获取本地商店文件成功");
			}

			byte[] data = new byte[inputStream.available()];

			inputStream.read(data);
			inputStream.close();
			String string = new String(data);

			DebugUtil.storeDebug(TAG, string);

			JSONObject jsonObject = new JSONObject(string);

			addCommonJsonProduct(jsonObject, Constant.GROUP_DISCOUNT);
			addCommonJsonProduct(jsonObject, Constant.GROUP_HOT_SALE);
			addCommonJsonProduct(jsonObject, Constant.GROUP_NEW);
			
		} catch (IOException e) {
			
			e.printStackTrace();
		} catch (JSONException e) {
			
			e.printStackTrace();
		}
	}
	
	public void addCommonJsonProduct(JSONObject jsonObj, int group) {
		
		String jsonGroup = null;
		
		switch (group){
		
		case Constant.GROUP_NEW:
			jsonGroup = Constant.GROUP_JSON_PARSER_NEW;
			break;
			
		case Constant.GROUP_DISCOUNT:
			jsonGroup = Constant.GROUP_JSON_PARSER_DISCOUNT;
			break;
		
		case Constant.GROUP_HOT_SALE:
			jsonGroup = Constant.GROUP_JSON_PARSER_HOT_SALE;
			break;
		
		default:
			DebugUtil.dbDebug(TAG, 
					"this group is not defined ,please check! group:"+ group);
			return ;
		}
		
		try {
			
			JSONArray jsonArray = jsonObj.getJSONArray(jsonGroup);

			int productNum = jsonArray.length();

			Store store = getBrainWavesApplication().getStore();

			for (int i = 0; i < productNum; i++) {
				
				if ( group == Constant.GROUP_DISCOUNT 
						&& jsonArray.getJSONObject(i).getString("visiable").equals("true")) {
					//对于打折的产品，我们需要解析更多的信息
					
					JSONObject json = jsonArray.getJSONObject(i);
					String productName = json.getString(Constant.PRODUCT_ID);	
					Product product = store.getProductByName(productName);
					
					if (null != product) {
						
						product.getProductInfo()
							.setParentId(json.getString(Constant.JSON_ATTR_PARSER_PARENT_ID));
						product.getProductInfo().setDiscount(
								String.valueOf(json.getDouble(Constant.JSON_ATTR_PARSER_DISCOUNT)));
						product.getProductInfo().setOriginalPrice(
								String.valueOf(json.getDouble(Constant.JSON_ATTR_PARSER_OLD_PRICE)));
						
						String newPrice = 
								String.valueOf(json.getDouble(Constant.JSON_ATTR_PARSER_NEW_PRICE));
						product.getProductInfo().setPriceOfDollar(newPrice);
						
						product.getProductInfo().setPriceOfGold(
								ProductUtil.getTUSGold(newPrice));
						DebugUtil.debug(TAG, "new price" + product.getProductInfo()
								.getPriceOfDollar());
					}
					
					
					store.addGroupProduct(group, productName);
					
				}else {
					
					String productName = jsonArray.getJSONObject(i).getString(
							Constant.PRODUCT_ID);

					store.addGroupProduct(group, productName);
				}									
			}
		} catch (JSONException e) {
			
			e.printStackTrace();
		}

	}
	@Override
	public void onTitleMenuClicked(View v) {
			
	}

}
